package httpService

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"io"
	"io/ioutil"
	"os"
	"pm/util"
	"strconv"
	"syscall"
)
type uploadInfo struct {
	Hash string `json:"hash"`
	Path string `json:"path"`
	Name string `json:"name"`
}

var fileUpLoadMap = make(map[string]uploadInfo)

func FileUpload(c echo.Context)error{

	//获取参数
	hash := c.FormValue("hash")
	name := c.FormValue("name")
	uniqueId := c.FormValue("unique_id")
	total := c.FormValue("total")
	current := c.FormValue("current")
	totalNum,_ := strconv.Atoi(total)
	currentNum,_ := strconv.Atoi(current)
	if hash == "" || name == "" || uniqueId == ""{
		return c.JSON(200, map[string]interface{}{
			"status": 1,
			"msg":"参数错误",
		})
	}
	var fileData uploadInfo
	var tmpFile *os.File
	var err1 error
	if val,ok :=fileUpLoadMap[uniqueId];ok{
		fileData = val
		tmpFile, err1 = os.OpenFile(fileData.Path, syscall.O_CREAT|syscall.O_APPEND|syscall.O_RDWR, 0755)
	}else{
		if currentNum != 1{
			return c.JSON(200, map[string]interface{}{
				"status": 1,
				"msg":"文件上传失败无效文件",
			})
		}
		fileData.Hash = hash
		fileData.Name  = name
		tmpFile, err1 = ioutil.TempFile("", "tmp_upload_file")
		 fileData.Path = tmpFile.Name()
		fileUpLoadMap[uniqueId] = fileData
	}
	if err1 != nil{
		return c.JSON(200, map[string]interface{}{
			"status": 3,
			"msg":"打开临时文件失败",
		})
	}

	fh,err:=c.FormFile("file")
	if err != nil{
		return c.JSON(200, map[string]interface{}{
			"status": 2,
			"msg":"获取上传数据失败",
		})
	}
	uploadFile,_ := fh.Open()
	io.Copy(tmpFile, uploadFile)
	tmpFile.Sync()

	tmpFile.Close()
	if totalNum == currentNum{
		if util.GetFileMd5(fileData.Path) != hash{
			fmt.Println(util.GetFileMd5(fileData.Path))
			return c.JSON(200, map[string]interface{}{
				"status": 2,
				"msg":"文件校验失败",
			})
		}
		delete(fileUpLoadMap, uniqueId)
	}
	return c.JSON(200, map[string]interface{}{
		"status": 0,
		"msg":"",
		"file":fileData.Path,
	})
}
